package com.freewater.javabase.demo.network.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(6666);
        System.out.println("Server is running...");
        while (true) {
            Socket accept = ss.accept();
            System.out.println("Connected from " + accept.getRemoteSocketAddress());
            Handler handler = new Handler(accept);
            handler.start();
        }
    }

    static class Handler extends Thread {
        private Socket socket;

        public Handler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (OutputStream outputStream = socket.getOutputStream()) {
                try (final InputStream inputStream = socket.getInputStream()) {
                    handle(inputStream, outputStream);
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioException) {

                }
            }
            System.out.println("client [" + socket.getRemoteSocketAddress() + "] disconnected.");
        }

        private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            writer.write("hello\n");
            writer.flush();
            while (true) {
                final String line = reader.readLine();
                System.out.println("received: " + line);
                if ("bye".equals(line)) {
                    writer.write("bye\n");
                    writer.flush();
                    break;
                }
                writer.write("ok: " + line + "\n");
                writer.flush();
            }
        }
    }
}
